<template>
    <el-table
        id="inplans-table-inplans"
        ref="tableRef"
        :data="tableData"
        v-bind="tableDefaultAttribute"
        row-key="id"
        :max-height="tableHeight"
        table-layout="auto"
        @cell-dblclick="update"
        @sort-change="handleSortChange"
    >
        <template #empty>
            <span>无数据</span>
        </template>
        <el-table-column type="selection" width="55" :align="'center'" />
        <template v-for="col in tableColumns" :key="col.prop">
            <el-table-column
                v-if="!col.isHidden"
                :align="col.align"
                :prop="col.prop"
                :label="col.label"
                :formatter="col.formatter"
                :type="col.type"
                :fixed="col.fixed"
                :width="col.width"
            >
            </el-table-column>
        </template>
    </el-table>
    <el-button-group class="bg">
        <el-space>
            <!-- <el-button
                class="btn"
                type="primary"
                :icon="Plus"
                @click="add"
                >增加</el-button
            > -->
            <AddBtn @click="add" :formData="paramData"></AddBtn>
            <!-- <el-button
                class="btn"
                type="primary"
                :icon="Delete"
                @click="onDelete"
                >删除</el-button
            > -->
            <DelBtn @click="onDelete"></DelBtn>
            <!-- <el-button
                class="btn"
                type="primary"
                :icon="Search"
                @click="onQuery"
                >查询</el-button
            > -->
            <SearchBtn @click="onQuery"></SearchBtn>
            <RefreshBtn @click="onRefresh"></RefreshBtn>
            <!-- <el-button
                class="btn"
                type="primary"
                :icon="Bell"
                @click="onPreCntr"
                >预定箱号</el-button
            > -->
            <NormalBtn @click="onPreCntr" :text="'预定箱号'"></NormalBtn>
            <!-- <el-button
                class="btn"
                type="primary"
                :icon="Search"
                @click="importCntr"
                >计划箱导入</el-button
            > -->
            <div>
                <el-upload
                    ref="uploadInplanRef"
                    action="/upload/importinplans"
                    :auto-upload="true"
                    accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                    :limit="1"
                    v-loading="inPlanLoading"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload1"
                    :on-exceed="handleExceed1"
                    :on-success="handleSuccess1"
                >
                    <template #trigger>
                        <el-button type="primary">导入进场计划</el-button>
                    </template>
                </el-upload>
            </div>
            <div>
                <el-upload
                    ref="uploadInplanAndCntrRef"
                    action="/upload/importinplanandcntr"
                    :auto-upload="true"
                    accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                    :limit="1"
                    v-loading="inPlanAndCntrLoading"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload2"
                    :on-exceed="handleExceed2"
                    :on-success="handleSuccess2"
                >
                    <template #trigger>
                        <el-button type="primary">导入进场计划及箱号</el-button>
                    </template>
                </el-upload>
            </div>
            <div>
                <el-upload
                    ref="uploadRef"
                    action="/upload/importinplancntrs"
                    :data="{ planID: `${importCntrparam.plan_id}` }"
                    :auto-upload="true"
                    accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                    :limit="1"
                    v-loading="loading"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :on-exceed="handleExceed"
                    :on-success="handleSuccess"
                >
                    <template #trigger>
                        <el-button type="primary" disabled>导入计划进场箱</el-button>
                    </template>
                </el-upload>
            </div>
            <el-dropdown @command="handleCommand">
                <el-button type="primary">
                    导出 Excel<el-icon class="el-icon--right"
                        ><arrow-down
                    /></el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="current"
                            >当前页</el-dropdown-item
                        >
                        <el-dropdown-item command="all">全部</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
            <!-- <el-button type="primary" @click="tour = true">介绍</el-button> -->
        </el-space>
    </el-button-group>
    <div class="page">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[50, 100, 150, 200]"
            layout="sizes, prev, pager, next, total"
            :total="totalnum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
        <!-- <Page :onRefresh="onRefresh"></Page> -->
    </div>
    <el-dialog
        v-model="dialogUpdateVisible"
        title="进场计划维护"
        draggable
        destroy-on-close
        :center="true"
        width="90%"
    >
        <InPlan
            :plan="paramData"
            @create="onAdded"
            @update="onUpdated"
            @close="onCloseDialog"
        >
        </InPlan>
    </el-dialog>
    <el-dialog
        v-model="dialogPreCntrVisible"
        title="计划预定箱号"
        draggable
        destroy-on-close
        :center="true"
        width="90%"
    >
        <PlanPreCntr
            :truck_sn=paramAddPreCntrs.plan_id :plan_type="paramAddPreCntrs.plan_type"
        >
        </PlanPreCntr>
    </el-dialog>
    <!-- <el-dialog
        v-model="dialogImportVisible"
        title="计划箱导入"
        draggable
        destroy-on-close
        :center="true"
        width="60%"
    >
        <InPlanGateIn :data="importCntrparam" @close="onCloseDialog">
        </InPlanGateIn>
    </el-dialog> -->
    <el-dialog
        v-model="dialogQueryVisible"
        title="进场计划查询"
        draggable
        destroy-on-close
    >
        <QueryForm
            :queryItems="queryItems"
            :tableID="tableRef!.$el.id"
            @yh-closedialog="onCloseDialog"
        ></QueryForm>
    </el-dialog>
</template>
<script setup lang="ts" name="InPlans">
import { ref, reactive, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import {
    ElMessage,
    ElMessageBox,
    ElTable,
    genFileId,
} from 'element-plus';
import {
    isEmpty,
    forEach,
    forEachRight,
    includes,
    findIndex,
    omit,
} from 'lodash';
import type { InPlanModel } from '@/common/types/container';
import {
    tableDefaultAttribute,
    useTableInfo,
    tableColumnDefault,
} from '@/hooks/useTable';
import type { QueryItem, TableColumn } from '@/common/types/app';
import { Request } from '@/app/request';
import {
    pickQueryFromTable,
    exportExcel
} from '@/common/tools';
import { tableMaxHeightAdjust } from '@/common/const';
import type {
    TableInstance,
    UploadInstance,
    UploadProps,
    UploadRawFile,
} from 'element-plus';

import { useAppStore } from '@/store/app';
import { transFormatter, formatDate } from '@/common/tools';
import InPlan from './InPlan.vue';
import PlanPreCntr from './PlanPreCntr.vue';
import SearchBtn from '@/components/button/SearchBtn.vue';
import RefreshBtn from '@/components/button/RefreshBtn.vue';
import AddBtn from '@/components/button/AddBtn.vue';
import DelBtn from '@/components/button/DelBtn.vue';
import NormalBtn from '@/components/button/NormalBtn.vue';
// import Page from '@/components/tables/Page.vue';
const { cntrOper, cntrOwner, cntrDam, cyCfs, SelectOptionYN, cntrGateInStat } = storeToRefs(useAppStore());
// const store = useSelectOptionStore();
// const SelectOptionCntrOperCod  = await store.SelectOptionCntrOperCod;


const tableRef = ref<TableInstance>();
const uploadRef = ref<UploadInstance>();
const uploadInplanRef = ref<UploadInstance>();
const uploadInplanAndCntrRef = ref<UploadInstance>();
const loading = ref(false);
const inPlanLoading = ref(false);
const inPlanAndCntrLoading = ref(false);
const tableData = ref<Array<InPlanModel>>([]);
const paramData = reactive<InPlanModel>({});
const paramAddPreCntrs = reactive<{
    plan_id: number,
    plan_type: string
}>({ plan_id: 0, plan_type: ''});
const importCntrparam = reactive<{
    plan_id?: number;
    plan_name?: string;
}>({});
const tableHeight = ref(600);
const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'cntr_oper_cod') {
        data = cntrOper.value;
    } else if (column['property'] === 'stat_cod') {
        data = cntrGateInStat.value;
    } else if (column['property'] === 'dam_id') {
        data = cntrDam.value;
    } else if (column['property'] === 'cfs_cod') {
        data = cyCfs.value;
    } else if (column['property'] === 'cntr_owner') {
        data = cntrOwner.value;
    } else if (column['property'] === 'finish_id') {
        data = SelectOptionYN.value;
    } else if (column['property'] === 'need_email') {
        data = SelectOptionYN.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'id',
        label: '计划号',
        fixed: 'left',
        formFieldItemType: 'input',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'plan_name',
        label: '计划名称',
        sortable: 'custom',
        fixed: 'left',
        formFieldItemType: 'input',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'plan_date',
        label: '预计进场日期',
        sortable: 'custom',
        formatter: formatDate,
        formFieldItemType: 'date',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 8,
        prop: 'stat_cod',
        label: '作业目的',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrGateInStat.value,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'cntr_siz_cod',
        label: '箱尺寸',
        sortable: 'custom',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 6,
        prop: 'cntr_typ_cod',
        label: '箱型',
        sortable: 'custom',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 7,
        prop: 'cntr_num',
        label: '箱量',
        sortable: 'custom',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 8,
        prop: 'cntr_oper_cod',
        label: '供应商',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrOper.value,
        width: 200,
    },

    {
        ...tableColumnDefault,
        order: 10,
        prop: 'cfs_cod',
        label: '站点',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cyCfs.value,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 11,
        prop: 'bill_no',
        label: '提箱单号',
        sortable: 'custom',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 12,
        prop: 'dam_id',
        label: '箱况',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrDam.value,
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 11,
        prop: 'in_reason',
        label: '进箱原因',
        sortable: 'custom',
        width: 200,
    },
    /* {
        ...tableColumnDefault,
        order: 13,
        prop: 'from_plac',
        label: '陆运起运地点',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: place,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 13,
        prop: 'to_plac',
        label: '陆运接收地点',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: place,
        width: 200,
    }, */

    {
        ...tableColumnDefault,
        order: 15,
        prop: 'cntr_owner',
        label: '箱主',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrOwner.value,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 16,
        prop: 'cntr_work_num',
        label: '已作业箱量',
        sortable: 'custom',
        width: 120,
    },
    {
        ...tableColumnDefault,
        order: 12,
        prop: 'finish_id',
        label: '完成',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionYN.value,
        width: 80,
    },
    /* {
        ...tableColumnDefault,
        order: 16,
        prop: 'free_days',
        label: '免费堆存天数',
        sortable: 'custom',
        width: 120,
    },
    {
        ...tableColumnDefault,
        order: 16,
        prop: 'day_rate',
        label: '堆存费率',
        sortable: 'custom',
        width: 120,
    }, */
    {
        ...tableColumnDefault,
        order: 12,
        prop: 'need_email',
        label: '发送邮件',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionYN.value,
        width: 120,
    },
    /* {
        ...tableColumnDefault,
        order: 17,
        prop: 'spec_no',
        label: '特殊记录号',
        sortable: 'custom',
        width: 200,
    }, */
    {
        ...tableColumnDefault,
        order: 18,
        prop: 'remark',
        label: '备注',
        sortable: 'custom',
        width: 400,
    },
]);
// const createActionName = ref('进场计划增加');
// const updateActionName = ref('进场计划修改');

const dialogQueryVisible = ref(false);
const dialogUpdateVisible = ref(false);
const dialogImportVisible = ref(false);
const dialogPreCntrVisible = ref(false);
let queryWhere = {};

const onRefresh = async () => {
    const req = new Request('进场计划查询', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        order: orders,
        ...queryWhere,
    });
    const r = await req.post();

    totalnum.value = r.ext;
    tableData.value.length = 0;

    if (!isEmpty(r.obj)) {
        tableData.value = r.obj;
    }
};
const {
    currentPage,
    orders,
    pageSize,
    totalnum,
    handleSizeChange,
    handleCurrentChange,
    handleSortChange,
} = useTableInfo(onRefresh);
onMounted(() => {
    tableHeight.value =
        window.innerHeight - tableMaxHeightAdjust;
});
const add = () => {
    // initObjectProperty(paramData);
    dialogUpdateVisible.value = true;
};
const update = (row: any) => {
    Object.assign(paramData, row);
    dialogUpdateVisible.value = true;
};
const onAdded = (data: InPlanModel) => {
    tableData.value.unshift(data);
};
const onUpdated = (data: InPlanModel) => {
    const i = findIndex(tableData.value, (o) => {
        return o.id === data.id;
    });
    if (i > -1) {
        Object.assign(tableData.value[i], omit(data, ['id']));
    } else {
        ElMessage.error('修改失败');
    }
};

const onCloseDialog = async (arg?: any) => {
    
    
    if (dialogUpdateVisible.value) {
        dialogUpdateVisible.value = false;
    }
    if (dialogImportVisible.value) {
        dialogImportVisible.value = false;
    }
    if (dialogPreCntrVisible.value) {
        dialogPreCntrVisible.value = false;
    }
    if (dialogQueryVisible.value) {
        // 查询
        currentPage.value = 1;
        queryWhere = arg;
        onRefresh();

        dialogQueryVisible.value = false;
    }
};

const onDelete = async () => {
    const rows: Array<InPlanModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择要删除数据',
        });
        return;
    }
    const ids = Array<number>();
    const labels = Array<string>();
    forEach(rows, (v: InPlanModel) => {
        ids.push(v.id as number);
        labels.push(v.plan_name as string);
    });

    const msg = labels.join(',     ');
    // const delids = ids.join(',');
    const cr = await ElMessageBox.confirm(msg, '确认删除如下计划', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('进场计划删除', { ids });
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(tableData.value, (v: InPlanModel, i: number) => {
                if (includes(ids, v.id)) {
                    tableData.value.splice(i, 1);
                }
            });
        }
    }
};
const onQuery = () => {
    dialogQueryVisible.value = true;
};
const onPreCntr = () => {
    const rows: Array<InPlanModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length !== 1) {
        ElMessage.info({
            message: '请选择一个计划',
        });
        return;
    }

    paramAddPreCntrs.plan_id = rows[0].id as number;
    paramAddPreCntrs.plan_type = rows[0].stat_cod as string;
    dialogPreCntrVisible.value = true;
}
const queryItems: Array<QueryItem> = pickQueryFromTable(tableColumns);
const handleCommand = async (command: string | number | object) => {
    if (command === 'current') {
        exportExcel('inplans-table-inplans');
    } else {
        const columns = [];
        for (let index = 0; index < tableColumns.length; index++) {
            const element = tableColumns[index];
            columns.push(element.prop);
        }
        const req = new Request('导出进场计划查询', {
            order: orders,
            ...queryWhere,
            excelColumn: columns,
        });
        const r = await req.post();
        if (!isEmpty(r.obj)) {
            // tableData.value = r.obj;
            // const url = r.obj; // 后端提供的下载接口
            window.open(r.obj, '_blank');
        }
    }
};

const beforeAvatarUpload = (rawFile: UploadRawFile) => {
    return new Promise<boolean>((resolve, reject) => {
        const rows: Array<InPlanModel> = tableRef.value?.getSelectionRows() || [];
        if (rows.length !== 1) {
            ElMessage.info({
                message: '请选择一个计划',
            });
            return reject(false);
        } else {
            importCntrparam['plan_id'] = rows[0].id;
        }

        var reader = new FileReader();
        reader.readAsDataURL(rawFile);

        if (
            rawFile.type !== 'application/vnd.ms-excel' &&
            rawFile.type !==
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ) {
            ElMessageBox.alert('只能上传excel文件', '错误', {
                confirmButtonText: '确定',
                type: 'error',
            });
            loading.value = false;
            return reject(false);
        } else if (rawFile.size / 1024 / 1024 > 2) {
            ElMessageBox.alert('文件大小不能超过2M!', '错误', {
                confirmButtonText: '确定',
                type: 'error',
            });
            loading.value = false;
            return reject(false);
        }

        return resolve(true);
    });
};
const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadRef.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    uploadRef.value!.handleStart(file);
};

const handleSuccess = (response: any) => {
    if (response.code > 0) {
        uploadRef.value!.clearFiles();
        ElMessageBox.alert(response.msg, '消息', {
            confirmButtonText: '确定',
            type: 'success',
        });
        tableData.value.forEach(element => {
            if (element.id === importCntrparam['plan_id']) {
                element.cntr_work_num = (element.cntr_work_num ?? 0) + response.ext;
            }
        });
        onRefresh();
    } else {
        ElMessageBox.alert(response.msg, '错误', {
            confirmButtonText: '确定',
            type: 'error',
        });
    }
    loading.value = false;
};
const beforeAvatarUpload1 = (rawFile: UploadRawFile) => {
    return new Promise<boolean>((resolve, reject) => {
        
        var reader = new FileReader();
        reader.readAsDataURL(rawFile);

        if (
            rawFile.type !== 'application/vnd.ms-excel' &&
            rawFile.type !==
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ) {
            ElMessageBox.alert('只能上传excel文件', '错误', {
                confirmButtonText: '确定',
                type: 'error',
            });
            inPlanLoading.value = false;
            return reject(false);
        } else if (rawFile.size / 1024 / 1024 > 2) {
            ElMessageBox.alert('文件大小不能超过2M!', '错误', {
                confirmButtonText: '确定',
                type: 'error',
            });
            inPlanLoading.value = false;
            return reject(false);
        }

        return resolve(true);
    });
};
const handleExceed1: UploadProps['onExceed'] = (files) => {
    uploadInplanRef.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    uploadInplanRef.value!.handleStart(file);
};

const handleSuccess1 = (response: any) => {
    if (response.code > 0) {
        uploadInplanRef.value!.clearFiles();
        ElMessageBox.alert(response.msg, '消息', {
            confirmButtonText: '确定',
            type: 'success',
        });
        onRefresh();
    } else {
        ElMessageBox.alert(response.msg, '错误', {
            confirmButtonText: '确定',
            type: 'error',
        });
    }
    inPlanLoading.value = false;
};
const beforeAvatarUpload2 = (rawFile: UploadRawFile) => {
    return new Promise<boolean>((resolve, reject) => {
        
        var reader = new FileReader();
        reader.readAsDataURL(rawFile);

        if (
            rawFile.type !== 'application/vnd.ms-excel' &&
            rawFile.type !==
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ) {
            ElMessageBox.alert('只能上传excel文件', '错误', {
                confirmButtonText: '确定',
                type: 'error',
            });
            inPlanAndCntrLoading.value = false;
            return reject(false);
        } else if (rawFile.size / 1024 / 1024 > 2) {
            ElMessageBox.alert('文件大小不能超过2M!', '错误', {
                confirmButtonText: '确定',
                type: 'error',
            });
            inPlanAndCntrLoading.value = false;
            return reject(false);
        }

        return resolve(true);
    });
};
const handleExceed2: UploadProps['onExceed'] = (files) => {
    uploadInplanAndCntrRef.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    uploadInplanAndCntrRef.value!.handleStart(file);
};

const handleSuccess2 = (response: any) => {
    if (response.code > 0) {
        uploadInplanAndCntrRef.value!.clearFiles();
        ElMessageBox.alert(response.msg, '消息', {
            confirmButtonText: '确定',
            type: 'success',
        });
        onRefresh();
    } else {
        ElMessageBox.alert(response.msg, '错误', {
            confirmButtonText: '确定',
            type: 'error',
        });
    }
    inPlanAndCntrLoading.value = false;
    
};
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}

</style>
